<template>
  <div>
    <div class="clearflex">
      <el-button class="fl-right" size="small" type="primary" @click="relation">确 定</el-button>
    </div>
    <el-tree
      ref="resourceTree"
      :data="resourceTreeData"
      :default-checked-keys="resourceTreeIds"
      :props="resourceDefaultProps"
      default-expand-all
      highlight-current
      node-key="id"
      show-checkbox
      @check="nodeChange"
    >
      <template #default="{ node , data }">
        <span class="custom-tree-node">
          <span>{{ node.label }}</span>
        </span>
      </template>
    </el-tree>

  </div>
</template>

<script setup>
import { getMenuResourceList, saveMenuResourceList } from '@/api/menu'
import { nextTick, ref } from 'vue'
import { ElMessage } from 'element-plus'

//接收父组件传来的值
const props = defineProps({
  row: {
    default: function() {
      return {}
    },
    type: Object
  }
})
//定义一个变量来接收父组件传来的方法
const emit = defineEmits(['changeRow'])

const resourceTreeData = ref([])
const resourceTreeIds = ref([])
const needConfirm = ref(false)
const resourceDefaultProps = ref({
  children: 'children',
  label: 'description'
})

const init = async() => {
  {
	  const res = await getMenuResourceList({menuId: props.row.id})
	  if (res.code === 0) {
		  const resources = res.data
		  resourceTreeData.value = buildResourceTree(resources)
		  
		  resourceTreeIds.value = []
		  resources.forEach(item => {
			  if(item.menuId === props.row.id){
				  resourceTreeIds.value.push(item.id)
			  }
		  })
	  }
  }
}

// 创建resource树方法
const buildResourceTree = (resources) => {
  const resourceObj = {}
  resources &&
        resources.forEach(item => {
			item.description = item.name + "[" + item.method + "]" + item.remark
          if (Object.prototype.hasOwnProperty.call(resourceObj, item.groupName)) {
            resourceObj[item.groupName].push(item)
          } else {
            Object.assign(resourceObj, { [item.groupName]: [item] })
          }
        })
  const resourceTree = []
  for (const key in resourceObj) {
	  let description = key
	  if(!description){
		  description = "未知"
	  }
    const treeNode = {
      ID: key,
      description: description + '组',
      children: resourceObj[key]
    }
    resourceTree.push(treeNode)
  }
  return resourceTree
}

init()

const nodeChange = () => {
  needConfirm.value = true
}
// 暴露给外层使用的切换拦截统一方法
const enterAndNext = () => {
  relation()
}
// 关联树 确认方法
const resourceTree = ref(null)
const relation = async() => {
  const checkArr = resourceTree.value.getCheckedKeys(true)
  const res = await saveMenuResourceList({
    ids: checkArr,
    id: props.row.id
  })
  if (res.code === 0) {
	needConfirm.value = false
    ElMessage({
      type: 'success',
      message: '资源保存成功!'
    })
  }
}

defineExpose({ enterAndNext, needConfirm })
</script>

<script>

export default {
  name: 'Resources'
}
</script>

<style lang="scss" scope>
.custom-tree-node{
  span+span{
    margin-left: 12px;
  }
}
</style>
